<template>
  <!--  查询 -->
  <div>
    <el-button @click="showNurselevelDialog" type="primary" style="width: 100px; margin-left: 50px;font-weight: bolder; font-size: 16px">
      登&emsp;记
    </el-button>
  </div>
  <!--  显示所有客户信息 table自动循环-->
  <div>{{errorMessage}}</div>
  <el-table :data="nurselevelList">
    <el-table-column label="序号" type="index" width="60px"></el-table-column>
    <el-table-column prop="levelName" label="护理级别" width="80px"></el-table-column>
    <el-table-column prop="levelStatus" label="级别状态" width="80px" align="center">
      <template #default="scope">
        <span :style="{
          color: scope.row.levelStatus === 1 ? '#67C23A' : '#F56C6C',
          fontWeight: '500'
        }">
          {{ scope.row.levelStatus === 1 ? '在用' : '停用' }}
        </span>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="120px">
      <template #default="scope">
        <el-button
            v-if="scope.row.levelStatus === 1"
            type="success"
            @click="changeStatus(scope.row, 2)"
        >
          启用
        </el-button>
        <el-button
            v-else
            type="danger"
            @click="changeStatus(scope.row, 1)"
        >
          禁用
        </el-button>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="120px">
      <template #default="{row}">
        <router-link :to="{ name: 'NurseItem', query: { nurselevelid: row.id }}">
          <el-button type="primary">查看详情</el-button>
        </router-link>
      </template>
    </el-table-column>
    <el-table-column  label="操作" width="120px">
      <template #default="scope">
        <el-button type="primary" @click="showContentDialog(scope.row.id)">添加内容</el-button>
      </template>
    </el-table-column>
  </el-table>

  <div class="example-pagination-block">
    <el-pagination background
                   v-model:current-page="pageContains.pageNum"
                   v-model:page-size="pageContains.pageSize"
                   :page-sizes="[10,20,30,50,100]"
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="pageContains.total"
                   @size-change="handleSizeChange"
                   @current-change="handlePageChange"
    />
  </div>

  <!--  客户信息对话框 -->
  <el-dialog v-model="nurselevelDialog" :title="dialogTitle">
    <el-form :model="curNurselevel">
      <el-form-item label="护理级别">
        <el-col :span="11">
          <el-input v-model="curNurselevel.levelName"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="级别状态">
        <el-col :span="11">
          <el-select v-model="curNurselevel.status">
            <el-option
                v-for="item in statusOptions"
                :label="item.label"
                :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-form-item>
    </el-form>
    <el-button @click="optOne()">{{buttonOpt}}</el-button>
  </el-dialog>


  <!-- 添加护理项目对话框 -->
  <el-dialog v-model="addContentDialog" title="添加护理项目">
    <el-form :model="contentForm">
      <el-form-item label="护理项目">
        <el-select v-model="contentForm.selectedItem" placeholder="请选择护理项目">
          <el-option
              v-for="item in nursingOptions"
              :key="item.id"
              :label="item.nursingName"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="addItemToLevel">添加</el-button>
  </el-dialog>

</template>

<script setup>
import {ref, onMounted, reactive} from "vue";
import http from '@/axios/http';
import qs from "qs";
import router from "@/util/router";
import {ElMessage} from "element-plus";



let statusOptions = ref([
  {
    label: '1',
    value: 1
  },{
    label: '2',
    value: 2
  }
])
// 存放用户数据集合
let nurselevelList = ref([]);

let nursingOptions = ref({});
//报错提示
let errorMessage = ref("")

//模糊查询绑定的 客户名称
let queryName = ref("")

//对话框显示控制
let nurselevelDialog = ref(false)

let nurselevelcontentDialog = ref(false)

//客户信息，或者编辑已有客户的 绑定数据
let curNurselevel = ref({});

//登记、修改客户信息弹出框的 标题和操作按钮  显示文字
let dialogTitle = reactive("")
let buttonOpt = reactive("")

//对话框操作类型：1：添加 2：编辑
let dialogOptType = reactive(1)
let size = 10; //当前显示多少行
let pageNum = 1; // 当前页码
let pageSize = 10; //每页显示行数

//当前页码信息
let pageContains = ref({})


const addContentDialog = ref(false);
const contentForm = reactive({
  selectedItem: null,
  currentLevelId: null
});

// 修改showContentDialog方法
function showContentDialog(nurselevelid) {
  contentForm.currentLevelId = nurselevelid;
  contentForm.selectedItem = null;
  getNursingnameData();
  addContentDialog.value = true;
}

// 添加护理项目到等级
function addItemToLevel() {
  if (!contentForm.selectedItem) {
    ElMessage.warning('请选择护理项目');
    return;
  }

  const param = {
    levelId: contentForm.currentLevelId,
    itemId: contentForm.selectedItem
  };

  http.post('/lyy/add_item_to_level', param)
      .then(res => {
        const result = res.data;
        if(result.result === 'success') {
          ElMessage.success('添加成功');
          addContentDialog.value = false;
          getAllNurselevels(); // 刷新列表
        } else {
          ElMessage.error(result.error || '添加失败');
        }
      })
      .catch(err => {
        ElMessage.error('请求失败：' + err.message);
      });
}


function changeStatus(row, newStatus) {
  const param = {
    id: row.id,
    levelStatus: newStatus
  };

  http.post('/lyy/update_status', param)
      .then(res => {
        const result = res.data;
        if(result.result === 'success') {
          row.levelStatus = newStatus; // 更新状态
          ElMessage.success('状态更新成功');
        } else {
          errorMessage.value = result.error || '状态更新失败';
        }
      })
      .catch(err => {
        errorMessage.value = '请求失败：' + err.message;
      });
}

function getNursingnameData(){
  //获取下拉框的数据
  http.post('/lyy/get_all_nursingname').then(
      (res)=>{
        let result = res.data;
        // 返回结果传给 nursingOptions
        if(result.result === 'success'){
          nursingOptions.value = result.data;
        } else {
          errorMessage.value = result.error;
        }
      }
  )

}


//根据客户姓名模糊查询客户信息
function queryByName(){

  let param = {
    nursingName: queryName.value
  }

  http.post('/lyy/get_nurselevels_by', param).then(
      (res)=>{
        let result = res.data;
        // 返回结果传给 nurselevelList
        if(result.result === 'success'){
          nurselevelList.value = result.data;
        } else {
          errorMessage.value = result.error;
        }

      }
  )
}

//单击登录按钮事件
function showNurselevelDialog(){
  dialogTitle = "录入护理等级";
  buttonOpt="录入"
  //弹出客户信息对话框
  nurselevelDialog.value = true;
  dialogOptType = 1 //设置当前操作类型标志是 录入

}

//关闭客户信息对话框
function closeNurselevelDialog(){
  nurselevelDialog.value = false;
}




//页面初始化
onMounted(
    ()=>{

      init();
    }
)

function init(){
  //查询所有用户信息
  getAllNurselevels();
  //查询需要的字典（{标志1: 值1, 标志2: 值2}）
  //用的时候取 字典[字段值（字典标志）]
}


function getAllNurselevels(){
  let params = ref({
    size: size,
    pageNum: pageNum,
    pageSize: pageSize
  })

  http.post('/lyy/get_all_nurselevels', params.value).then(
      (res)=>{
        let result = res.data;
        // 返回结果传给 nurselevelList
        if(result.result === 'success'){
          pageContains.value = result.data;
          //pageContains.list = null;
          nurselevelList.value = result.data.list;

        } else {
          errorMessage.value = result.error;
        }

      }
  )
}




function recordOne(){
  let param = curNurselevel.value;
  http.post('/lyy/add_one_nurselevel', param).then(
      (res)=>{
        let result = res.data;
        // 返回结果传给 nurselevelList
        if(result.result === 'success'){
          //关闭对话框
          closeNurselevelDialog()

          //刷新客户列表
          getAllNurselevels();
        } else {
          errorMessage.value = result.error;
        }

      }
  )
}

function showLevelContent(nurselevelid){
  //根据id查询客户信息
  getNurselevelInfo(nurselevelid)

  getNursingnameData();
  //显示对话框
  console.log(nurselevelid)
  nurselevelcontentDialog.value = true;
  dialogTitle = "增加护理内容";
  buttonOpt="增加"

  dialogOptType = 2 //设置当前操作类型标志是 修改

}



//显示编辑对话框
function showEditDialog(nurselevelid){
  //根据id查询客户信息
  getNurselevelInfo(nurselevelid)

  //显示对话框
  console.log(nurselevelid)
  nurselevelDialog.value = true;
  dialogTitle = "护理内容修改";
  buttonOpt="修改"

  dialogOptType = 2 //设置当前操作类型标志是 修改

}

function getNurselevelInfo(nurselevelid){
  let param = {
    nurselevelid : nurselevelid
  }
  http.post('/lyy/getnurselevelby_id', qs.stringify(param)).then(
      (res)=>{
        let result = res.data;
        // 返回结果传给 nurselevelList
        if(result.result === 'success'){
          curNurselevel.value = result.data;
        } else {
          errorMessage.value = result.error;
        }

      }
  )
}

//删除客户
function removeOne(nurselevelid){
  let param = {
    nurselevelid : nurselevelid
  }
  http.post('/lyy/removenurselevel_by_id', qs.stringify(param)).then(
      (res)=>{
        let result = res.data;
        // 返回结果传给 nurselevelList
        if(result.result === 'success'){
          getAllNurselevels();
        } else {
          errorMessage.value = result.error;
        }

      }
  )
}

function editOne(){
  let param = curNurselevel.value;
  http.post('/lyy/modifynurselevelby_id', param).then(
      (res)=>{
        let result = res.data;
        if(result.result === 'success'){
          //curNurselevel.value = result.data;
          closeNurselevelDialog();
          getAllNurselevels();

        } else {
          errorMessage.value = result.error;
        }

      }
  )
}

function optOne(){
  if(dialogOptType === 1){
    recordOne()
  } else if(dialogOptType === 2) {
    editOne()
  }
}

//分页处理
const handlePageChange = (pageNum1)=>{
  pageNum = pageNum1
  getAllNurselevels()
}

const handleSizeChange = (pageSize1)=>{
  pageSize = pageSize1
  getAllNurselevels()
}

</script>

<style scoped>

</style>